from machine import Pin, SPI
import st7789

import unicn_16x16
import unicn_24x24
import unicn_32x32
import unicn_40x40
#import NotoSans_32 as noto_sans


def main():

    def center(font, s, row, color=st7789.WHITE):
        screen = tft.width()                     # get screen width
        width = tft.write_len(font, s)           # get the width of the string
        if width and width < screen:             # if the string < display
            col = tft.width() // 2 - width // 2  # find the column to center
        else:                                    # otherwise
            col = 0                              # left justify

        tft.write(font, s, col, row, color)      # and write the string

    try:
        # initialize the SPI
        spi = SPI(1, baudrate=30000000, sck=Pin(18), mosi=Pin(19))

        # confgure the display
        tft = st7789.ST7789(
            spi,
            135,
            240,
            reset=Pin(23, Pin.OUT),
            cs=Pin(5, Pin.OUT),
            dc=Pin(16, Pin.OUT),
            backlight=Pin(4, Pin.OUT),
            rotation=3)

        # enable display and clear screen
        tft.init()
        tft.fill(st7789.BLACK)

        # center the name of the first font, using the font
        row = 3
        # center(noto_sans, "NotoSans", row, st7789.RED)
        # row += noto_sans.HEIGHT

        tft.text_ch(unicn_16x16, "你好啊", 10, row, st7789.RED, st7789.BLACK)
        row += unicn_16x16.HEIGHT

        tft.text_ch(unicn_32x32, "秋水共长天一色", 10, row, 0x780f, st7789.BLACK)
        row += unicn_32x32.HEIGHT

        tft.text_ch(unicn_24x24, "秋水共长天一色", 10, row, 0x03ef, st7789.BLACK)
        row += unicn_24x24.HEIGHT

        tft.text_ch(unicn_40x40, "落霞与孤鹜齐飞", 10, row, 0xFFE0, st7789.BLACK)


    finally:
        # shutdown spi
        if 'spi' in locals():
            spi.deinit()


main()